<template>
<div>
  <!-- 查询条件 -->
  <el-form :inline="true" class="mb-4">
    <el-form-item label="优惠券类型" class="mr-4">
      <el-select v-model="queryParams.discountType" clearable style="width: 120px">
        <el-option label="店铺券" value="SHOP" />
        <el-option label="商品券" value="PRODUCT" />
      </el-select>
    </el-form-item>
<!--    <el-form-item label="状态" class="mr-4">-->
<!--      <el-select v-model="queryParams.status" clearable style="width: 100px">-->
<!--        <el-option label="可用" value="0" />-->
<!--        <el-option label="已下架" value="1" />-->
<!--      </el-select>-->
<!--    </el-form-item>-->
    <el-form-item>
      <el-button type="primary" @click="loadData">查询</el-button>
    </el-form-item><el-form-item>
    <el-button type="success" @click="showCreateDialog" icon="Plus">发放新优惠券</el-button>
  </el-form-item>
  </el-form>

  <!-- 数据表格 -->
  <el-table :data="coupons" border stripe style="width: 100%;">
    <!-- 优惠券ID -->
    <el-table-column prop="discountId" label="优惠券ID" width="80" />

    <!-- 优惠券名称 -->
    <el-table-column prop="discountName" label="名称" width="180" />

    <!-- 优惠券类型 -->
    <el-table-column label="类型" width="120">
      <template #default="{row}">
        <el-tag :type="row.discountType === 'SHOP' ? 'success' : 'warning'" effect="light">
          {{ row.discountType }}
        </el-tag>
      </template>
    </el-table-column>

    <!-- 店铺ID -->
    <el-table-column prop="shopId" label="店铺ID" width="80" />

    <!-- 商品ID -->
    <el-table-column prop="productId" label="商品ID" width="80" />

    <!-- 折扣值 -->
    <el-table-column prop="discountValue" label="折扣值" width="120">
      <template #default="{row}">
        {{ row.discountValue }}折
      </template>
    </el-table-column>

    <!-- 开始时间 -->
    <el-table-column prop="startDate" label="开始时间" width="160">
      <template #default="{row}">
        {{ formatDate(row.startDate) }}
      </template>
    </el-table-column>

    <!-- 结束时间 -->
    <el-table-column prop="endDate" label="结束时间" width="160">
      <template #default="{row}">
        {{ formatDate(row.endDate) }}
      </template>
    </el-table-column>

    <!-- 最大用户领取数量 -->
    <el-table-column prop="maxUserClaims" label="最大用户领取数量" width="160" />

    <!-- 创建时间 -->
    <el-table-column prop="createdAt" label="创建时间" width="160">
      <template #default="{row}">
        {{ formatDate(row.createdAt) }}
      </template>
    </el-table-column>

    <!-- 更新时间 -->
    <el-table-column prop="updatedAt" label="更新时间" width="160">
      <template #default="{row}">
        {{ formatDate(row.updatedAt) }}
      </template>
    </el-table-column>

    <!-- 状态 -->
    <el-table-column label="状态" width="100">
      <template #default="{row}">
        <el-tag :type="row.status ? 'success' : 'danger'" effect="plain">
          {{ row.status ? '可用' : '已下架' }}
        </el-tag>
      </template>
    </el-table-column>

    <!-- 折扣策略 -->
    <el-table-column prop="discountStrategy" label="折扣策略" width="120">
      <template #default="{row}">
        {{ row.discountStrategy === 1 ? '直扣' : '折扣' }}
      </template>
    </el-table-column>

    <!-- 满减金额 -->
    <el-table-column prop="fullReduction" label="直扣金额" width="120" />

    <!-- 剩余数量 -->
    <el-table-column prop="discountNum" label="剩余数量" width="120" />

    <!-- 操作 -->
    <el-table-column label="操作" width="260" fixed="right">
      <template #default="{row}">
        <el-button size="small" @click="showReplenishDialog(row)">补充</el-button>
        <el-button type="warning" size="small" @click="showEditDialog(row)">编辑</el-button>
        <el-button
          type="danger"
          size="small"
          @click="deactivateCoupon(row)"
          :disabled="!row.status">
          下架
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <el-pagination
    v-model:current-page="queryParams.page"
    v-model:page-size="queryParams.size"
    :total="total"
    :page-sizes="[10, 20, 50]"
    layout="total, sizes, prev, pager, next, jumper"
    class="mt-4 justify-end"
    @current-change="loadData"
    @size-change="handleSizeChange"
  />

  <!-- 创建/编辑对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
    <el-form-item label="名称" prop="discountName">
      <el-input v-model="formData.discountName" placeholder="请输入优惠券名称" />
    </el-form-item>
    <el-form-item label="类型" prop="discountType">
      <el-tag :type="formData.discountType === 'SHOP' ? 'success' : 'warning'" effect="light" style="margin-right: 10px">
        {{ formData.discountType }}
      </el-tag>
        <el-switch
          v-model="isShowStrategy2"
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
          @change="handleStrategyChange2"
        />
    </el-form-item>

    <el-form-item label="开始时间" prop="validityPeriod">
      <el-date-picker
        v-model="formData.startDate"
        type="date"
        placeholder="Pick a day"
        :size="size"
      />
    </el-form-item>
    <el-form-item label="结束时间" prop="validityPeriod">
      <el-date-picker
        v-model="formData.endDate"
        type="date"
        placeholder="Pick a day"
        :size="size"
      />
    </el-form-item>
    <!-- 动态显示商品ID输入框 -->
    <el-form-item v-if="isShowStrategy2" label="商品ID" prop="productId">
      <el-input v-model="formData.productId" placeholder="请输入商品ID" />
    </el-form-item>
    <el-form-item label="策略选择">
      <el-tag :type="formData.discountStrategy === 'SHOP' ? 'success' : 'warning'" effect="light" style="margin-right: 10px">
        {{ formData.discountStrategy === 1 ? '直扣' : '折扣' }}
      </el-tag>

      <el-switch
        v-model="isShowStrategy"
        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
        @change="handleStrategyChange"
      />
    </el-form-item>

    <!-- 动态显示满减策略字段 -->
    <el-form-item v-if="!isShowStrategy" label="直扣金额" prop="fullReduction">
      <el-input-number
        v-model="formData.fullReduction"
        :min="1"
        :step="1"
        controls-position="right"
        class="w-full"
      />
    </el-form-item>
    <el-form-item v-else label="折扣值" prop="discountValue">
      <el-input-number
        v-model="formData.discountValue"
        :min="1"
        :max="9.9"
        :step="0.1"
        controls-position="right"
        class="w-full"
      />
    </el-form-item>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleCreate">保存</el-button>
    </template>
  </el-dialog>
  <!-- 补充对话框 -->
  <el-dialog v-model="replenishVisible" title="补充优惠券" width="400px">
    <el-form>
      <el-form-item label="补充数量">
        <el-input-number v-model="replenishAmount" :min="1" controls-position="right" class="w-full" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="replenishVisible.value = false">取消</el-button>
      <el-button type="primary" @click="handleReplenish(currentCoupon.discountId, replenishAmount)">确认补充</el-button>
    </template>
  </el-dialog>
</div>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import {ElMessage, ElMessageBox, type  FormInstance} from 'element-plus'
import {DiscountAPI, updateOrderStatus} from '@/common/net/api'
import type { DiscountInfo, CreateDiscountParams, DiscountQueryParams } from '@/common/types/discountTypes'
import { useLoginStore } from '@/stores/login'

const s = useLoginStore()
const formRef = ref<FormInstance>()
// 查询参数
const queryParams = reactive<DiscountQueryParams>({
  page: 1,
  size: 10,
  discountType: '',
  shopId: s.brand.brandId // 从store或token获取当前店铺ID
})
let isShowStrategy = ref(false)
let isShowStrategy2 = ref(false)
const coupons = ref([])
const total = ref(0)
const dialogVisible = ref(false)
const replenishVisible = ref(false)
const currentCoupon = ref({})
const replenishAmount = ref(1)

let isEdit = ref(false)
// 表单数据
let formData = reactive<DiscountInfo>({
  discountName: '',
  discountType: 'SHOP',
  discountValue: 1,
  maxUserClaims: 100,
  startDate: new Date(),
  endDate: new Date(),
  discountStrategy: 1,
  fullReduction: 100,
  discountNum: 100,
  productId: 1 // 添加商品ID字段
})
// 分页大小变化处理
const handleSizeChange = (size: number) => {
  queryParams.size = size
  loadData()
}
const showReplenishDialog = (row: any) => {
  currentCoupon.value = row;
  replenishAmount.value = 1; // 默认补充数量为1
  replenishVisible.value = true;
};
const formatDate = (dateArray: number[]) => {
  if (!dateArray || dateArray.length < 3) return '';
  const [year, month, day, hour = 0, minute = 0, second = 0] = dateArray;
  return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')} ${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:${String(second).padStart(2, '0')}`;
};
const showEditDialog = (row: any) => {
  formData = reactive<DiscountInfo>({
    discountId: row.discountId, // 添加优惠券ID
    discountName: row.discountName,
    discountType: row.discountType,
    discountValue: row.discountValue,
    maxUserClaims: row.maxUserClaims,
    startDate: row.startDate,
    endDate: row.endDate,
    discountStrategy: row.discountStrategy,
    fullReduction: row.fullReduction,
    discountNum: row.discountNum,
    productId: row.productId
  });
  isShowStrategy2.value=row.discountType=='PRODUCT'
  isShowStrategy.value=row.discountStrategy==2
  console.log(row.discountType)
  console.log(isShowStrategy)
  console.log(row.discountStrategy)
  console.log(isShowStrategy2)
  dialogVisible.value = true;
  isEdit.value=true
};
const showCreateDialog = () => {
  formData = reactive<DiscountInfo>({
    discountName: '',
    discountType: 'SHOP',
    discountValue: 1,
    maxUserClaims: 100,
    startDate: new Date(),
    endDate: new Date(),
    discountStrategy: 1,
    fullReduction: 100,
    discountNum: 100
  });
  isEdit.value=false
  console.log(111)
  dialogVisible.value = true
}
// 加载数据
const loadData = async () => {
  try {
    const res = await DiscountAPI.getList(queryParams)
    if (res.data.state) {
      coupons.value = res.data.data.records
      total.value = res.data.data.total
    } else {
      ElMessage.error(res.data.msg || '加载失败')
    }
  } catch (error) {
    ElMessage.error('网络异常，请稍后再试')
  }
}
// 创建优惠券
const handleCreate = async () => {
  if (isEdit.value){
    try {
      const res = await DiscountAPI.update({
        ...formData
      })
      if (res.data.state) {
        ElMessage.success('操作成功')
        dialogVisible.value = false
        await loadData()
      } else {
        ElMessage.error(res.data.msg || '操作失败')
      }
    } catch (error) {
      ElMessage.error('网络异常，请稍后再试')
    }
  }else{
    try {
      const res = await DiscountAPI.createBrand({
        ...formData,
        shopId: queryParams.shopId // 关联当前店铺
      })
      if (res.data.state) {
        ElMessage.success('优惠券创建成功')
        dialogVisible.value = false
        await loadData()
      } else {
        ElMessage.error(res.data.msg || '创建失败')
      }
    } catch (error) {
      ElMessage.error('网络异常，请稍后再试')
    }
  }
}

// 下架优惠券
const deactivateCoupon = async (row:any) => {
  ElMessageBox.confirm('确定下架？', '下架', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {

    try {
      const res = await DiscountAPI.deactivateBrand(row.discountId)
      if (res.data.state) {
        ElMessage.success('优惠券已下架')
        await loadData()
      } else {
        ElMessage.error(res.data.msg || '下架失败')
      }
    } catch (error) {
      ElMessage.error('网络异常，请稍后再试')
    }

  });
}

// 补充库存
const handleReplenish = async (id, amount) => {
  console.log(id)
  console.log(amount)
  try {
    const res = await DiscountAPI.replenish(id, amount)
    if ( res.data.state) {
      ElMessage.success('库存补充成功')
      replenishVisible.value=false
      await loadData()
    } else {
      ElMessage.error(res.data.msg || '补充库存失败')
    }
  } catch (error) {
    ElMessage.error('网络异常，请稍后再试')
  }
}
const handleStrategyChange = () => {
  console.log('当前策略:', formData.discountStrategy);
  formData.discountStrategy=formData.discountStrategy==1?2:1
  console.log('当前策略2:', formData.discountStrategy);
};
const handleStrategyChange2 = () => {
  formData.discountType=formData.discountType=='SHOP'?'PRODUCT':'SHOP'
};
loadData()
</script>

<style scoped>
.app-container {
  max-width: 1200px;
  margin: 20px auto;
}

:deep(.el-table__header) th {
  background-color: #f8f9fa;
  font-weight: 600;
}

:deep(.el-pagination) {
  margin-top: 20px;
  justify-content: flex-end;
}

.text-blue-600 {
  color: #2563eb;
}
</style>
